package top.jiangqiang.qianyi.common.jackson;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;

/**
 * 将Long类型序列化为字符串
 */
@JsonComponent
public class HandlerLongJsonComponent {

    public static class Serializer extends JsonSerializer<Long> {

        @Override
        public void serialize(Long value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            if (value == null) {
                jsonGenerator.writeString((String) null);
            } else {
                jsonGenerator.writeString(value.toString());
            }
        }
    }

    public static class Deserializer extends JsonDeserializer<Long> {

        @Override
        public Long deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
            ObjectCodec codec = jsonParser.getCodec();
            String value = codec.readValue(jsonParser, String.class);
            if (value == null) {
                return null;
            } else {
                return Long.valueOf(value);
            }
        }
    }

}